package cn.didi.feidi.androidorder.adapter;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.databinding.ItemHomePageRecyclerViewBinding;
import cn.didi.feidi.androidorder.db.ShoppingCarDao;
import cn.didi.feidi.androidorder.model.ShoppingCar;
import cn.didi.feidi.androidorder.model.WaterBucket;

/**
 * Created by jinxiong on 2017/8/23.
 */

public class MainHomePageRecyclerViewAdapter extends RecyclerView.Adapter<MainHomePageRecyclerViewAdapter.ViewHolder> {

    private static final String TAG = "MainHomePageRecyclerVie";
    private final boolean DEBUG = false;
    ArrayList<WaterBucket> waterBuckets;
    AsyncSession asyncSession;
    ArrayList<WaterBucket> collectionList;
    private Callback mCallback;
    private Fragment fragment;
    private Activity activity;

    public MainHomePageRecyclerViewAdapter(Fragment fragment) {
        this.fragment = fragment;
        this.activity = fragment.getActivity();
        this.waterBuckets = new ArrayList<>();
        collectionList = new ArrayList<>();
        asyncSession = OrderApplication.getDaoSession().startAsyncSession();
    }

    public void setCallback(Callback callback) {
        mCallback = callback;
    }

    public void getCollectionsFromDb() {

        asyncSession.setListenerMainThread(new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {

                if (operation.isFailed()) {
                    Toast.makeText(MainHomePageRecyclerViewAdapter.this.activity, "获取数据失败", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (operation.getType() == AsyncOperation.OperationType.QueryList) {

                    Log.d(TAG, "onAsyncOperationCompleted:  查询收藏");
                    Object obj = operation.getResult();

                    if (obj != null && obj instanceof List) {
                        Log.d(TAG, "onAsyncOperationCompleted: 获取本地收藏商品成功");
                        collectionList.clear();
                        collectionList.addAll((Collection<? extends WaterBucket>) obj);
                        notifyDataSetChanged();
                    }
                }
            }
        });

        asyncSession.queryList(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(WaterBucket.class)).build());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        ItemHomePageRecyclerViewBinding binding = DataBindingUtil.
                inflate(activity.getLayoutInflater(), R.layout.item_home_page_recycler_view, parent, false);

        ViewHolder viewHolder = new ViewHolder(binding.getRoot());
        viewHolder.setBinding(binding);

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {


        if (waterBuckets.size() < 0) {
            return;
        }

        Glide.with(fragment)
                .load(waterBuckets.get(position).getPicUrl())
                .placeholder(R.drawable.logo)
                .into(holder.getBinding().waterBucketIv);

        holder.getBinding().itemHomePageCollectTv.setText("收藏");

        final int id = waterBuckets.get(position).getBucketTypeId().intValue();

        if (collectionList != null && collectionList.size() > 0) {

            int size = collectionList.size();
            for (int i = 0; i < size; i++) {

                if (collectionList.get(i).getBucketTypeId().intValue() == id) {
                    holder.getBinding().itemHomePageCollectTv.setText("已收藏");
                    break;
                }
            }

        }


        //收藏点击事件
        holder.getBinding().itemHomePageCollectTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final TextView textView = (TextView) v;
                if ("已收藏" == textView.getText().toString()) {
                    Toast.makeText(activity, "已加入收藏,不用重复添加", Toast.LENGTH_SHORT).show();
                    return;
                }
                final WaterBucket insertObject = waterBuckets.get(position);
                Log.d(TAG, "onClick: " + insertObject);
                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                    @Override
                    public void onAsyncOperationCompleted(AsyncOperation operation) {
                        if (operation.isFailed()) {
                            Toast.makeText(activity, "收藏失败", Toast.LENGTH_SHORT).show();
                            Log.d(TAG, "onAsyncOperationCompleted: " + operation.getThrowable().getMessage());
                            return;
                        }
                        if (operation.getType() == AsyncOperation.OperationType.Insert) {
                            Log.d(TAG, "onAsyncOperationCompleted: " + operation.getParameter().getClass().getSimpleName());
                            Log.d(TAG, "onAsyncOperationCompleted: " + operation.getParameter());
                            if (operation.getParameter() instanceof WaterBucket) {
                                collectionList.add((WaterBucket) operation.getParameter());
                                textView.setText("已收藏");
                                Toast.makeText(activity, "成功加入收藏", Toast.LENGTH_SHORT).show();
                            }

                        }

                    }
                });

                asyncSession.insert(insertObject);

            }
        });


        holder.getBinding().itemHomePageAddShoppingCarLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final ShoppingCar shoppingCar = new ShoppingCar();
                shoppingCar.convertData(waterBuckets.get(position));


                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                    @Override
                    public void onAsyncOperationCompleted(AsyncOperation operation) {


                        if (operation.isFailed()) {
                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (operation.getType() == AsyncOperation.OperationType.QueryUnique) {

                            if (operation.getResult() == null) {
                                shoppingCar.setBuyCount(1);

                                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                    @Override
                                    public void onAsyncOperationCompleted(AsyncOperation operation) {
                                        if (!operation.isFailed()) {
                                            Toast.makeText(activity, "成功加入购物车 ", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                                asyncSession.insert(shoppingCar);

                            } else {

                                ShoppingCar shopCar = (ShoppingCar) operation.getResult();
                                shopCar.setBuyCount(shopCar.getBuyCount() + 1);

                                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                    @Override
                                    public void onAsyncOperationCompleted(AsyncOperation operation) {

                                        if (!operation.isFailed()) {
                                            Toast.makeText(activity, "成功加入购物车 ", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });


                                asyncSession.update(shopCar);
                            }
                        }
                    }


                });

                asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(ShoppingCar.class))
                        .where(ShoppingCarDao.Properties.BucketTypeId.eq(shoppingCar.getBucketTypeId()))
                        .build());

            }
        });

        holder.getBinding().setWaterBucket(waterBuckets.get(position));

    }

    @Override
    public int getItemCount() {
        return waterBuckets.size();
//        return 10;
    }

    public void setWaterBuckets(ArrayList<WaterBucket> waterBuckets) {

        this.waterBuckets.clear();

        if (waterBuckets != null) {
            this.waterBuckets.addAll(waterBuckets);
        }

        notifyDataSetChanged();
    }


    public void addWaterBuckets(ArrayList<WaterBucket> waterBuckets) {

        if (waterBuckets != null) {
            this.waterBuckets.addAll(waterBuckets);
            notifyDataSetChanged();
        }

    }

    public interface Callback {
        void callBack(WaterBucket waterBucket);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private ItemHomePageRecyclerViewBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
        }

        public ItemHomePageRecyclerViewBinding getBinding() {
            return binding;
        }

        public void setBinding(ItemHomePageRecyclerViewBinding binding) {
            this.binding = binding;
        }
    }
}
